package com.extremelylargepackage.level;

import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import android.graphics.Bitmap;
import android.util.Log;

import com.extremelylargepackage.GameState;
import com.extremelylargepackage.entity.Enemy;
import com.extremelylargepackage.entity.Entity;
import com.extremelylargepackage.entity.ScrollingBackground;

/**
 * Represents a playable level.
 */
public class Level implements Serializable
{
	private transient GameState _gameState;

	private ScrollingBackground _background;
	private String _name;
	private float _backgroundDx, _backgroundDy;

	private LinkedList<LevelEvent> _events;

	public Level() {
		_events = new LinkedList<LevelEvent>();
		_events.add(Wave.dummyWave());
	}

	public void addEvent(LevelEvent w)
	{
		_events.add(w);
	}
	
	public void setBackground(ScrollingBackground background)
	{
		_background = background;
	}

	public void setGameState(GameState gameState)
	{
		_gameState = gameState;
		for(LevelEvent wave: _events)
		{
			if(wave.getEnemies() != null)
			{
				for(Enemy enemy : wave.getEnemies().values())
					enemy.setPlayer(_gameState.getPlayer());
			}
			if(wave instanceof CommandEvent)
				((CommandEvent)wave).setGameState(gameState);
		}
	}

	/**
	 * Progresses the level by the specified time. Returns true if the level is "finished",
	 * false otherwise.
	 * @param time
	 * @return level status
	 */
	public void updateLevel(long time)
	{
		if(_events.isEmpty())
			return;

		LevelEvent currentWave = _events.peek();
		currentWave.updateState(time);
		if(currentWave.finished()) {
			_events.poll();

			if(_events.isEmpty())
				return;

			Collection<Enemy> enemies = _events.peek().getEnemies().values();
			for(Enemy enemy : enemies) {
				_gameState.spawnEnemy(enemy);
			}

			Collection<Entity> scenery = _events.peek().getScenery();
			for(Entity sceneryObj : scenery) {
				_gameState.spawnScenery(sceneryObj);
			}
		}
	}
	
	public boolean levelComplete()
	{
		if(_events.isEmpty())
		{
			if(_gameState.getEnemies().size() > 0)
				return false;
			return true;
		}
		return false;
	}
	
	public ScrollingBackground getBackground()
	{
		return _background;
	}
	
	public void setName(String name)
	{
		_name = name;
	}
	
	public String getName()
	{
		return _name;
	}
	
	public Queue<LevelEvent> getEventQueue()
	{
		return _events;
	}
	
	public void replaceEvent(int location, LevelEvent event)
	{
		_events.remove(location);
		_events.add(location, event);
	}
}
